#include <httpRequest.h>
#include <regex>
#include <json/json.h>

namespace http {

    StringMap &HttpRequest::getDataMap() {
        using namespace std;

        regex reg_key_velue(".*=.*");
        if (!regex_match(body, reg_key_velue)) {
            data_map.clear();
            return data_map;
        }
        regex                 reg_and("&");
        sregex_token_iterator post(body.begin(), body.end(), reg_and, -1);
        decltype(post)        end;
        for (; post != end; post++) {
            const std::string &temp  = post->str();
            auto               post1 = temp.find_first_of('=');
            if (post1 != std::string::npos) {
                data_map.emplace(std::make_pair(temp.substr(0, post1), temp.substr(post1 + 1)));
            }
        }
        return data_map;
    }

    bool HttpRequest::isJson() {
        Json::Value param;
        if (operator[]("Content-Type") == "application/json") {
            Json::String                      jsErrors;
            Json::CharReaderBuilder           jcrBuilder;
            std::unique_ptr<Json::CharReader> jcReader(jcrBuilder.newCharReader());

            if (!jcReader->parse(this->body.c_str(), this->body.c_str() + this->body.length(), &param, &jsErrors)) {
                return false;
            }
        }
        return true;
    }
}  // namespace http
